package org.example.springboot.controller;

import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.example.springboot.common.page.PageResult;
import org.example.springboot.common.utils.Result;
import org.example.springboot.constants.IrrigationTypeConstants;
import org.example.springboot.entity.ColDevice;
import org.example.springboot.entity.ColDeviceDataSet;
import org.example.springboot.entity.IrrigationLog;
import org.example.springboot.query.IrrigationUnitQuery;
import org.example.springboot.service.IrrigationLogService;
import org.example.springboot.service.IrrigationUnitService;
import org.example.springboot.utils.WeatherApiClient;
import org.example.springboot.vo.IrrigationUnitVO;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * @author Fz
 * @since 1.0.0 2024-07-31
 */
@Slf4j
@RestController
@RequestMapping("/irrigation-unit")
@AllArgsConstructor
public class IrrigationUnitController {

    private final IrrigationUnitService irrigationUnitService;

    private final IrrigationLogService irrigationLogService;

    private final HttpServletRequest request;

    @PostMapping("page")
    public Result<PageResult<IrrigationUnitVO>> page(@RequestBody IrrigationUnitQuery query) {
        PageResult<IrrigationUnitVO> page = irrigationUnitService.page(query);
        return Result.ok(page);
    }

    @GetMapping("/getIrrigationUnitById")
    @Operation(summary = "信息")
    public Result<IrrigationUnitVO> getIrrigationUnitById(@RequestParam Long id) {
        return Result.ok(irrigationUnitService.getIrrigationUnitById(id));
    }

    @PostMapping("/save")
    @Operation(summary = "保存")
    public Result<String> save(@RequestBody IrrigationUnitVO vo) {
        if (irrigationUnitService.checkItExists(vo.getUnitCode())) {
            irrigationUnitService.doSave(vo);
            IrrigationLog irrigationLog = new IrrigationLog();
            irrigationLog.setUuid(UUID.randomUUID().toString());
            irrigationLog.setUserId(Long.valueOf(request.getHeader("Uid")));
            irrigationLog.setOperationDetail("灌溉单元信息设置");
            irrigationLog.setOperationType("01");
            switch (vo.getType()) {
                case IrrigationTypeConstants.MOISTURE_CONTROL:
                    irrigationLog.setDeviceNo(String.valueOf(vo.getRationTypeMsg().get("equipmentName") != null
                            ? vo.getRationTypeMsg().get("equipmentName") : ""));
                    break;
                case IrrigationTypeConstants.ET:
                    irrigationLog.setDeviceNo(String.valueOf(vo.getETTypeMsg().get("equipmentName") != null
                            ? vo.getETTypeMsg().get("equipmentName") : ""));
                    break;
                default:
                    irrigationLog.setDeviceNo("");
            }
            irrigationLogService.save(irrigationLog);
            return Result.ok();
        }
        return Result.error("灌溉单元信息已存在!");
    }

    @PostMapping("/update")
    @Operation(summary = "编辑")
    public Result<String> update(@RequestBody IrrigationUnitVO vo) {
        irrigationUnitService.doSave(vo);
        IrrigationLog irrigationLog = new IrrigationLog();
        irrigationLog.setUuid(UUID.randomUUID().toString());
        irrigationLog.setUserId(Long.valueOf(request.getHeader("Uid")));
        irrigationLog.setOperationDetail("修改灌溉单元信息");
        irrigationLog.setOperationType("01");
        switch (vo.getType()) {
            case IrrigationTypeConstants.MOISTURE_CONTROL:
                irrigationLog.setDeviceNo(String.valueOf(vo.getRationTypeMsg().get("equipmentName") != null
                        ? vo.getRationTypeMsg().get("equipmentName") : ""));
                break;
            case IrrigationTypeConstants.ET:
                irrigationLog.setDeviceNo(String.valueOf(vo.getETTypeMsg().get("equipmentName") != null
                        ? vo.getETTypeMsg().get("equipmentName") : ""));
                break;
            default:
                irrigationLog.setDeviceNo("");
        }
        irrigationLogService.save(irrigationLog);
        return Result.ok();
    }

    @GetMapping("/delete")
    @Operation(summary = "删除")
    public Result<String> delete(@RequestParam Long id) {
        irrigationUnitService.delete(id);
        return Result.ok();
    }

    @PostMapping("/updateWaterVolumeInfo")
    @Operation(summary = "更新剩余水量信息")
    public Result<String> updateWaterVolumeInfo(@RequestBody IrrigationUnitVO vo) {
        irrigationUnitService.updateWaterVolumeInfo(vo);
        return Result.ok();
    }

    @PostMapping("/decisionCallbacks")
    @Operation(summary = "决策程序回调")
    public Result<String> decisionCallbacks(@RequestBody IrrigationUnitVO vo) {
        irrigationUnitService.decisionCallbacks(vo);
        return Result.ok();
    }



    @GetMapping("/queryDevicesByUserId")
    @Operation(summary = "根据用户ID查询对应设备列表")
    public Result<List<ColDevice>> queryDevicesByUserId(@RequestParam("userId") Long userId, @RequestParam("devType") Integer devType) {
        return Result.ok(irrigationUnitService.queryDevicesByUserId(userId, devType));
    }

    @GetMapping("/queryDeviceValueByNo")
    @Operation(summary = "根据设备编码查询对应设备值")
    public Result<List<ColDeviceDataSet>> queryDeviceValueByNo(@RequestParam("deviceId") Long deviceId) {
        return Result.ok(irrigationUnitService.queryDeviceValueByNo(deviceId));
    }

    @GetMapping("/checkDevice")
    @Operation(summary = "检查设备")
    public Result<Object> checkDevice() {
        irrigationUnitService.checkDevice();
        return Result.ok();
    }

    @SneakyThrows
    @GetMapping("/weatherInfo")
    @Operation(summary = "获取天气信息")
    public Result<Object> weatherInfo() {
        return Result.ok(WeatherApiClient.sendGetRequest("http://v1.yiketianqi.com/api?unescape=1&version=v63&appid=81191881&appsecret=J6qFGxVz&city=巴彦淖尔"));
    }



    @GetMapping("/setETCheck")
    @Operation(summary = "设置为ET决策时调用")
    public Result<String> setETCheck(@RequestParam String controlDevice) {
        irrigationUnitService.setETCheck(controlDevice);
        return Result.ok();
    }


    @GetMapping("/setCycleCheck")
    @Operation(summary = "设置为周期灌溉时调用")
    public Result<String> setCycleCheck(@RequestParam String controlDevice,@RequestParam String cycle) {
        irrigationUnitService.setCycleCheck(controlDevice,cycle);
        return Result.ok();
    }

    @GetMapping("/delTaskByJobId")
    @Operation(summary = "删除定时任务")
    public Result<String> delTaskByJobId(@RequestParam String controlDevice) {
        irrigationUnitService.delTaskByJobId(controlDevice);
        return Result.ok();
    }

    @GetMapping("/upCycleCron")
    public Result<String> upCycleCron() {
        irrigationUnitService.upCycleCron();
        return Result.ok();
    }

}